﻿using System;
using System.Web;
using System.Web.Services;
using BLL.BussinessClass;
using Model;
using System.Web.SessionState;
using System.Configuration;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections.Generic;
namespace AlltrustDinner
{
    public class ProcessRequestMoudle : IHttpModule
    {
        /// <summary>
        /// 您将需要在网站的 Web.config 文件中配置此模块
        /// 并向 IIS 注册它，然后才能使用它。有关详细信息，
        /// 请参见下面的链接: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpModule Members

        public void Dispose()
        {
            //此处放置清除代码。
        }

        public void Init(HttpApplication context)
        {
            // 下面是如何处理 LogRequest 事件并为其 
            // 提供自定义日志记录实现的示例
            //context.LogRequest += new EventHandler(OnLogRequest);
            context.AcquireRequestState += new EventHandler(this.Application_AcquireRequestState);
            context.Error += new EventHandler(this.Application_ErrorHandler);

        }

        private void Application_ErrorHandler(object sender, EventArgs e)
        {
            string extName = HttpContext.Current.Request.CurrentExecutionFilePathExtension;
            if (".ashx" != extName && ".aspx" != extName)
            {
                return;
            }
            StringBuilder errorSb = new StringBuilder();
            string FileName = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ErrorLogPath"].ToString());
            using (StreamWriter sw = new StreamWriter(FileName, true))
            {
                errorSb.Append("抛错时间：").AppendLine(DateTime.Now.ToString())
                       .Append("抛错文件：").AppendLine(HttpContext.Current.Request.CurrentExecutionFilePath)
                       .Append("抛错信息：").AppendLine(HttpContext.Current.Error.ToString()).AppendLine();
                sw.WriteLine(errorSb.ToString());
            }
            if (".aspx" == extName)
            {
                HttpContext.Current.Server.Transfer("/Pages/Error.aspx");
            }
            if (".ashx" == extName)
            {
                JavaScriptSerializer Serializer = new JavaScriptSerializer();
                Dictionary<string, string> result = new Dictionary<string, string>();
                result.Add("ApplicationError", "True");
                HttpContext.Current.Response.Write(Serializer.Serialize(result));
                HttpContext.Current.Response.End();
            }

        }

        #endregion

        [WebMethod(EnableSession = true)]
        public void Application_AcquireRequestState(Object source, EventArgs e)
        {

            if (null == HttpContext.Current.Session)
            {
                return;
            }
            USER user = null;
            UserBiz biz = new UserBiz();
            string extName = HttpContext.Current.Request.CurrentExecutionFilePathExtension;
            if (".ashx" == extName && null == HttpContext.Current.Session["CurrentUser"])
            {
                HttpContext.Current.Response.Redirect("/Pages/Default.aspx", true);
            }


            if (null != HttpContext.Current.Session["CurrentUser"])
            {
                user = HttpContext.Current.Session["CurrentUser"] as USER;
            }
            else
            {
                string userID = HttpContext.Current.User.Identity.Name;
                userID = userID.Substring(userID.IndexOf('\\') + 1);
                user = biz.GetUser(userID);
                if (null == user)
                {
                    user = new USER();
                    user.ID = userID;
                    user.NAME = userID;//待处理
                    biz.AddUser(user);
                }
                HttpContext.Current.Session.Add("CurrentUser", user);
            }

            HttpContext.Current.Session.Timeout = 10;
        }
        public void OnLogRequest(Object source, EventArgs e)
        {
            //可以在此处放置自定义日志记录逻辑
        }
    }
}
